import {PageContainer} from '@ant-design/pro-layout';
import ProForm, {ProFormRadio} from "@ant-design/pro-form";
import {Dropdown, Menu, message, Popconfirm} from 'antd';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable, {ActionType} from '@ant-design/pro-table';
import { useRef, useState } from "react";

import OrderDetailsModal from "@/pages/order/components/OrderDetailsModal";
import OrderRemarksModal from "@/pages/order/components/OrderRemarksModal";
import OrderRecordModal from "@/pages/order/components/OrderRecordModal";
import NoRefundModal from "@/pages/order/components/NoRefundModal";
import ImmediateRefundModal from "@/pages/order/components/ImmediateRefundModal";
import {DetectOrder, getAfterSale} from "@/services/ant-design-pro/order";
import {DownOutlined, QuestionCircleOutlined} from "@ant-design/icons";
import ProCard from '@ant-design/pro-card';
import './index.css'
import {isArray} from "lodash";

const AfterSalesOrder = () => {
    const [isShowOrderDetail, setIsShowOrderDetail] = useState(false)   // 订单详情模态框状态
    const [isShowOrderRecord, setIsShowOrderRecord] = useState(false)  // 订单记录模态框状态
    const [isShowOrderRemarks, setIsShowOrderRemarks] = useState(false)  // 订单备注模态框状态
    const [isShowImmediateRefund,setIsShowImmediateRefund] = useState(false) // 订单立即退款模态框
    const [isShowNoRefund,setIsShowNoRefund] = useState(false) // 订单不退款模态框
    const [orderStatusSearch, setOrderStatusSearch] = useState([]) // 订单状态搜索
    const [orderDetailId, setOrderDetailId] = useState(null)    // 订单详情id
    const [orderRecordId, setOrderRecordId] = useState(null)    // 订单记录id
    const [orderRemarksId, setOrderRemarksId] = useState(null)   // 订单备注id
    const [ImmediateRefundId, setImmediateRefundId] = useState(null)   // 立即退款id
    const [noRefundId, setNoRefundId] = useState(null)   // 不退款id
    const [refundOrderNumber,setRefundOrderNumber] = useState('')   // 立即退款订单号
    const [noRefundOrderNumber,setNoRefundOrderNumber] = useState('')   // 立即不退款订单号
    const [RefundOrderPrice,setRefundOrderPrice] = useState('')   // 立即退款价格
    const [OrderData, setOrderData] = useState({})   // 获取订单数量的数据
    const actionRef = useRef<ActionType>();  // 搜索状态更新

  const menu = (records) => {
        return (
            <Menu>
                <Menu.Item key={1}>
                    <p
                        onClick={async () => {
                          setIsShowOrderDetail(true)
                          setOrderDetailId(records.id)
                        }}
                    >
                        订单详情
                    </p>
                </Menu.Item>
                <Menu.Item key={2}>
                    <p
                        onClick={() => {
                          setIsShowOrderRecord(true)
                          setOrderRecordId(records.id)
                        }}
                    >
                        订单记录
                    </p>
                </Menu.Item>
                <Menu.Item key={3}>
                    <p
                        onClick={() => {
                            setIsShowOrderRemarks(true)
                            setOrderRemarksId(records.id)
                        }}
                    >
                        订单备注
                    </p>
                </Menu.Item>
                { records.state !== 'refunded' ?
                    <div>
                        <Menu.Item key={4}>
                            <p
                                onClick={() => {
                                    setIsShowImmediateRefund(true)
                                    setImmediateRefundId(records.id)
                                    setRefundOrderNumber(records.order_number)
                                    setRefundOrderPrice(records.pay_price)
                                }}
                            >
                                立即退款
                            </p>
                        </Menu.Item>
                        <Menu.Item key={5}>
                            <p
                                onClick={() => {
                                    setIsShowNoRefund(true)
                                    setNoRefundId(records.id)
                                    setNoRefundOrderNumber(records.order_number)
                               }}
                              >
                                不退款
                            </p>
                        </Menu.Item>
                    </div>
                : null
                }
                <Menu.Item key={6}>
                    {records.is_user_delete === 0 ?
                        <Popconfirm
                            key={records.id}
                                title="确定要删除此订单吗？ 删除将无法找回"
                                onConfirm={ async () => {
                                    await DetectOrder(records.id)
                                    message.success('订单删除成功')
                                    actionRef.current?.reload()
                                }}
                                okText="确定"
                                cancelText="取消"
                        >
                            <p>删除订单</p>
                        </Popconfirm>
                    :
                      <Popconfirm
                          title="用户还未删除,无法进行此操作 !!!"
                          icon={<QuestionCircleOutlined style={{ color: 'red' }} />}>
                          <p>删除订单</p>
                      </Popconfirm>
                    }
                </Menu.Item>
            </Menu>
        )
    };
    const columns: ProColumns = [
    {
        title: '订单号',
        dataIndex: 'order_number',
        align: 'center',
    },
    {
        title: '用户信息',
        dataIndex: 'userinfo',
        align: 'center',
        search: false,
        render: (_, record) => [
            <div>{record.user.nickname}</div>
        ]
    },
    {
        title: '商品信息',
        dataIndex: 'goodsInfo',
        search: false,
        align: 'center',
        render: (_, record) => {
            if (isArray(record.orderCartInfo?.cart_info)){
                return  record?.orderCartInfo?.cart_info.map(item=>{
                    return (
                        <div style={{fontSize:'10px', display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                            <img
                                style={{width:'40px',marginTop:'2px' }}
                                src={item.image_url}
                            />
                            <div>{item.info}</div>
                            <div>￥ {item.price} x { item.num}</div>
                        </div>
                    )
                })
            }else {
              return  <div style={{color:'#ccc'}}>本订单暂无商品信息</div>
            }
        }
    },
    {
        title: '实际支付',
        dataIndex: 'pay_price',
        search: false,
        align: 'center'
    },
    {
        title: '发起退款时间',
        dataIndex: 'refund_reason_time',
        valueType: 'dateTime',
        align: 'center',
    },
    {
        title: '退款状态',
        dataIndex: 'refund_status_text',
        align: 'center',
        search: false,
    },
    {
        title: '退款信息',
        dataIndex: 'content',
        align: 'center',
        search: false,
        width: 250,
        render: (_, records) => {
            return (
                <div style={{textAlign: 'left', paddingLeft: '40px'}}>
                    <span style={{color: '#f124c7', fontSize: '10px', fontWeight: 'bold'}}>申请退款</span>
                    <div style={{fontSize: '10px'}}>退款原因 : {records.refund_reason_wap_explain}</div>
                    <div style={{fontSize: '10px'}}>备注说明: {records.mark}</div>
                    <div style={{fontSize: '10px'}}>退款时间: {records.refund_reason_time}</div>
                    <span style={{fontSize: '10px'}}>退款凭证:</span>
                    <image src={records.refund_reason_wap_img}/>
                </div>
            )
        }
    },
    {
        title: '操作',
        align: 'center',
        search: false,
        width: 150,
        fixed: "right",
        render: (_, records) => {
            return (
                <Dropdown overlay={menu(records)}>
                    <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                        更多 <DownOutlined/>
                    </a>
                </Dropdown>
            )
        }
    },
    ];
    return (
        <PageContainer header={{breadcrumb: {}}}>
            <div style={{background: 'white', padding: '20px'}}>
                <ProForm
                    submitter={false}
                    onValuesChange={(values) => {
                        switch (values.radioButton) {
                            case '1' :
                                setOrderStatusSearch({
                                      ...orderStatusSearch,
                                      ...{refund_status: undefined }
                                  })
                                break;
                            case '2' :
                                setOrderStatusSearch({
                                      ...orderStatusSearch,
                                      ...{refund_status: 'Refund_only'}
                                  })
                                break;
                            case '3' :
                                setOrderStatusSearch({
                                        ...orderStatusSearch,
                                        ...{refund_status: 'Refund_return'}
                                  })
                                break;
                            case '4' :
                                setOrderStatusSearch({
                                        ...orderStatusSearch,
                                        ...{refund_status: 'Refuse_refund'}
                                })
                                break;
                            case '5' :
                                setOrderStatusSearch({
                                        ...orderStatusSearch,
                                        ...{refund_status: 'toBe_returned'}
                                })
                                break;
                            case '6' :
                                setOrderStatusSearch({
                                        ...orderStatusSearch,
                                        ...{refund_status: 'toBe_received'}
                                })
                                break;
                            case '7' :
                                setOrderStatusSearch({
                                        ...orderStatusSearch,
                                        ...{refund_status: 'refunded'}
                                })
                                break;
                        }
                        actionRef.current?.reload();
                    }}
                >
                    <ProCard>
                        <ProFormRadio.Group
                            name="radioButton"
                            label="订单状态:"
                            radioType="button"
                            options={[
                                {
                                    label: `全部  ${OrderData.order_all || ''}`,
                                    value: '1',
                                },
                                {
                                    label: `仅退款 ${OrderData.Refund_only || ''}`,
                                    value: '2',
                                },
                                {
                                    label: `退货退款 ${OrderData.Refund_return || ''}`,
                                    value: '3',
                                },
                                {
                                    label: `拒绝退款 ${OrderData.Refuse_refund || ''}`,
                                    value: '4',
                                },
                                {
                                    label: `商品待退款 ${OrderData.toBe_returned || ''}`,
                                    value: '5',
                                },
                                {
                                    label: `退货待收货 ${OrderData.toBe_received || ''}`,
                                    value: '6',
                                },
                                {
                                    label: `已退款 ${OrderData.refunded || ''}`,
                                    value: '7',
                                },
                            ]}
                        />
                    </ProCard>
                </ProForm>
                <div>
                    <ProTable
                        columns={columns}
                        scroll={{x: 1400}}
                        actionRef={ actionRef }
                        request={async (params = {}, sort, filter) => {
                            let {data, meta} = await getAfterSale({...params, ...sort, ...filter, ...orderStatusSearch})
                            setOrderData(meta.show)
                            return {
                                data,
                                success: true,
                            };
                        }}
                        rowKey="key"
                        dateFormatter="string"
                        search={{
                            labelWidth: 'auto',
                            optionRender: (searchConfig, formProps, dom) => [
                                ...dom.reverse(),
                            ],
                        }}
                    />
                </div>

                {isShowOrderDetail ?
                    <OrderDetailsModal
                        visible={isShowOrderDetail}
                        setVisible={setIsShowOrderDetail}
                        show={true}
                        id={orderDetailId}
                    />
                : null}
                { isShowOrderRecord ?
                    <OrderRecordModal
                        key={23}
                        visible={isShowOrderRecord}
                        setVisible={setIsShowOrderRecord}
                        id={orderRecordId}
                    />
                  : null
                }
                { isShowOrderRemarks ?
                    <OrderRemarksModal
                        visible={isShowOrderRemarks}
                        setVisible={setIsShowOrderRemarks}
                        id={orderRemarksId}
                        mack={() => {
                          actionRef.current?.reload();
                        }}
                    />
                  : null
                }
                {isShowImmediateRefund ?
                    <ImmediateRefundModal
                        visible={isShowImmediateRefund}
                        setVisible={setIsShowImmediateRefund}
                        orderNumber={refundOrderNumber}
                        price={RefundOrderPrice}
                        id={ImmediateRefundId}
                    />
                : null}
                {isShowNoRefund ?
                    <NoRefundModal
                        visible={isShowNoRefund}
                        setVisible={setIsShowNoRefund}
                        id={noRefundId}
                        orderNumber={noRefundOrderNumber}
                        noRefund={() => {
                          actionRef.current?.reload();
                        }}
                    />
                : null}
            </div>
        </PageContainer>
    );
};

export default AfterSalesOrder;
